<?php
// application/resources/Db.php
/**
 * Resource_Db
 *
 * demo-zf application
 *
 * @author Adam Pilacki <adam.pilacki@gmail.com>
 */
final class Resource_Db
    extends Lib_ResourceAbstract
{
    /**
     * Set configurations for db connections and models metadata
     *
     * No connections yet - lazy load
     *
     * @return true
     */
    protected final function _getResource()
    {
        /* use cache */
        $cache = Lib_Cache::getCacheForIni(240, array(APPLICATION_PATH . '/../configs/db.ini'), 'db');
        if (!$config = $cache->load(Lib_Cache::INI_DB_ID)) {
            $config = $this->_getConfig();
            $cache->save($config);
        }

        /* traverse all configurations and set in connection manager */
        foreach ($config->db as $key => $val) {
            AdamP_Model_Connection::setConfiguration($val, $key);
        }

        /* set up cache for models metadata */
        $frontendOptions = array(
            'automatic_serialization' => true,
            'caching' => $config->metadataCache->enabled, /* Cache on/off */
            'lifetime' => $config->metadataCache->lifetime
        );
        $backendOptions  = array(
            'cache_dir' => $config->metadataCache->dir,
            'hashed_directory_umask' => 0777,
            'cache_file_umask' => 0777,
        );
        $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
        Zend_Db_Table_Abstract::setDefaultMetadataCache(Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions));

        return true;
    }

    /**
     * Prepares config object and returns it
     *
     * @return Zend_Config_Ini
     */
    private function _getConfig()
    {
        /**
         * Set up config as merge of main and local
         */
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/../configs/db.ini', APPLICATION_ENV, true);
        try {
            $config->merge(new Zend_Config_Ini(APPLICATION_PATH . '/../configs/local/db.ini', APPLICATION_ENV));
        } catch (Zend_Config_Exception $e) {
            /* do nothing here... */
        }
        $config->setReadOnly();

        return $config;
    }
}